package com.dao.impl;

import com.dao.BaseDao;
import com.dao.UserDao;
import com.entity.User;
import com.entity.UserExample;
import com.mapper.UserMapper;
import com.page.PageInfo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
//@Component
public class UserDaoImpl extends BaseDao implements UserDao {
	@Resource
	UserMapper userMapper;
	@Resource
	private QueryRunner queryRunner;

	@Override
	public List<User> getAllUsers(PageInfo pageInfo) throws SQLException {
		int currPage = pageInfo.getCurrPage();
		int pageSize = pageInfo.getPageSize();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("start", (currPage-1)*pageSize);
		data.put("end", (currPage-1)*pageSize+pageSize);
		System.out.println("---------------"+pageSize+"----------------------");
		UserExample userExample = new UserExample();
		pageInfo.setItemCount((int) userMapper.countByExample(userExample));
		return userMapper.selectAllUsersByPage(data);
//		return queryRunner.query("select * from User", new BeanListHandler<User>(User.class));
	}
	
	public User getUserById(int uid) throws SQLException {
		User user = userMapper.selectByPrimaryKey(uid);
		return  user;
	}

	public List<User> getUsers(String uname) throws SQLException {
		return queryRunner.query("select * from User where uname=?", new BeanListHandler<User>(User.class), uname);
	}

	public int insertUser(User user) throws IllegalArgumentException, IllegalAccessException, SQLException {
//		Map<String, Object[]> map = insertEntity(user);
//		String sql = map.keySet().iterator().next();
//		Object[] params = map.get(sql);
//		return queryRunner.execute(sql,  params);
		return  userMapper.insertUser(user);
	}

	public int updateUser(User user) throws IllegalArgumentException, IllegalAccessException, SQLException,
			NoSuchFieldException, SecurityException {
//		Map<String, Object[]> map = updateEntity(user);
//		String sql = map.keySet().iterator().next();
//		Object[] params = map.get(sql);
//		return queryRunner.update(sql, params);
        return  userMapper.updateByPrimaryKeySelective(user);
	}

	public int delateUser(int uid){
		return  userMapper.deleteByPrimaryKey(uid);
	}
}
